<?php
// +----------------------------------------------------------------------
// | CLTPHP.Pro [系统设置]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2029 https://www.cltphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.cltphp.com/detail-140.html )
// +----------------------------------------------------------------------
// | Author: chichu <1109305987@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\model\SystemGroup;
use app\common\model\System as M;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Db;
use think\facade\View;

class System extends Base
{
    protected $validate = 'System';
    protected $validateSG = 'SystemGroup';

    public function treaty()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            $detail = $data['detail'];
            $r = Db::name("sale_setting")->where('key', 'treaty')->find();
            if (empty($r)) {
                Db::name("sale_setting")->insert([
                    "key" => 'treaty',
                    "value" => $detail
                ]);
            } else {
                Db::name("sale_setting")->where('key', 'treaty')->update([
                    "value" => $detail
                ]);
            }
            Cache::delete('sale_setting');
            return ['code' => 0, 'msg' => '保存成功'];
        } else {
            $detail = get_sale_setting('treaty');
            return view("", compact('detail'));
        }
    }
    public function secret()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            $detail = $data['detail'];
            $r = Db::name("sale_setting")->where('key', 'secret')->find();
            if (empty($r)) {
                Db::name("sale_setting")->insert([
                    "key" => 'secret',
                    "value" => $detail
                ]);
            } else {
                Db::name("sale_setting")->where('key', 'secret')->update([
                    "value" => $detail
                ]);
            }
            Cache::delete('sale_setting');
            return ['code' => 0, 'msg' => '保存成功'];
        } else {
            $detail = get_sale_setting('secret');
            return view("", compact('detail'));
        }
    }
    public function about()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            $detail = $data['detail'];
            $r = Db::name("sale_setting")->where('key', 'about')->find();
            if (empty($r)) {
                Db::name("sale_setting")->insert([
                    "key" => 'about',
                    "value" => $detail
                ]);
            } else {
                Db::name("sale_setting")->where('key', 'about')->update([
                    "value" => $detail
                ]);
            }
            Cache::delete('sale_setting');
            return ['code' => 0, 'msg' => '保存成功'];
        } else {
            $detail = get_sale_setting('about');
            return view("", compact('detail'));
        }
    }

    // 系统设置查看
    public function website()
    {
        //查找所有数据
        $system = M::getListField()->toArray();
        //格式化设置字段
        $system = sysgem_setup($system);
        //将数据重新分组
        $system = array_group2($system, 'group_id');
        //查找所有分组名称
        $systemGroup = SystemGroup::where(['status' => 1])->select()->toArray();
        $systemGroup = array_group($systemGroup, 'id');
        $view = [
            'system' => $system,
            'systemGroup' => $systemGroup,
        ];
        View::assign($view);
        return View::fetch();
    }

    // 系统设置提交
    public function websiteEdit()
    {
        $data = Request::except(['file'], 'post');
        //查找所有显示的数据（隐藏的数据无法修改，不再显示）
        $list = M::where('status', 1)->select()->toArray();
        //循环判断数据合法性
        foreach ($list as $k => $v) {
            $systemGroupStatus = SystemGroup::where('id', $v['group_id'])->field('status')->find();
            if ($systemGroupStatus['status'] == 0) {
                continue;// 当分组为隐藏状态时，不再进行修改
            }
            //判断是否必填
            if ($v['required'] == 1) {
                if (array_key_exists($v['field'], $data)) {
                    if (!$data[$v['field']]) {
                        return ['code' => 1, 'msg' => $v['name'] . '为必填项!'];
                    }
                } else {
                    return ['code' => 1, 'msg' => $v['name'] . '为必填项!'];
                }
            }
            //数据处理
            switch ($v['type']) {
                case 'checkbox'://复选框
                    if (array_key_exists($v['field'], $data)) {
                        $data[$v['field']] = is_array($data[$v['field']]) ? implode(",", $data[$v['field']]) : $data[$v['field']];
                    }
                    break;
                case 'datetime'://时间
                    $data[$v['field']] = strtotime($data[$v['field']]);
                    break;
                case 'image':
                    if (isset($data[$v['field'] . '_aid'])) {
                        setAttachment('system', $v['field'], $data[$v['field'] . '_aid'], $v['id']);
                    }
            }
        }
        foreach ($data as $k => $v) {
            //查找并进行修改
            $info = M::where('field', $k)->find();
            if ($info) {
//                $info->value = $v;
//                $info->save();
                M::update([
                    'value' => $v,
                    'update_time' => time()
                ], ['field' => $k]);
            }
        }
        \think\facade\Cache::delete('system_config');
        return ['code' => 0, 'msg' => '设置成功!'];
    }

    // 分组
    public function group()
    {
        if (request()->isPost()) {
            //全局查询条件
            $where = [];
            $key = input('post.key');
            if (!empty($key)) {
                $where[] = ['name|description', 'like', '%' . $key . '%'];
            }
            //分页
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $page = ['list_rows' => $pageSize, 'page' => $page];

            //排序
            $sort_order = input('sort_order') ? input('sort_order') : 'asc';
            $order = input('sort_order') ? [input('sort_by') => $sort_order] : ['sort' => $sort_order];
            //获取列表
            $list = SystemGroup::getList($where, $page, $order)->toArray();

            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        return view();
    }

    public function cf()
    {
        $data = input('post.');
        $result = SystemGroup::editSave($data);
        return $result;
    }

    // 添加分组
    public function add()
    {
        return view('form', ['info' => '']);
    }

    // 添加分组保存
    public function addSave()
    {
        $data = Request::except(['file'], 'post');
        $data['status'] = 1;
        $result = $this->validate($data, $this->validateSG);
        if (true !== $result) {
            // 验证失败 输出错误信息
            return ['code' => 1, 'msg' => $result];
        } else {
            $result = SystemGroup::addSave($data);
            return $result;
        }
    }

    // 分组修改
    public function edit()
    {
        $id = input('param.id');
        $info = SystemGroup::edit($id);
        $view = ['info' => $info];
        return view('form', $view);
    }

    // 分组修改保存
    public function editSave()
    {
        $data = Request::except(['file'], 'post');
        $result = $this->validate($data, $this->validateSG);
        if (true !== $result) {
            return ['code' => 1, 'msg' => $result];
        } else {
            $result = SystemGroup::editSave($data);
            return $result;
        }
    }

    // 删除
    public function del()
    {
        $id = Request::param('id');
        if ($id <= 3) {
            return ['code' => 1, 'msg' => '基础分组不可删除'];
        }
        // 启动事务
        Db::startTrans();
        try {
            Db::name('system_group')->where('id', input('id'))->delete();//删除分组
            Db::name('system')->where('group_id', input('id'))->delete();//删除该分组下的配置项
            // 提交事务
            Db::commit();
            return ['code' => 0, 'msg' => '删除成功！'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 1, 'msg' => '删除失败！'];
        }
    }
}